package com.hpc.Controller;

import Utils.JSONUtil;
import Utils.JWTUtil;
import Utils.ResultUtil;
import entity.ResultEnum;
import entity.user;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/ts/user/api")
public class commonController {
    @Resource
    private com.hpc.Service.userService userService;
    @Value("${headBaseUrl}")
    private String baseUrl;
//    http://localhost:8081/ts/article/articleImages/
    public static final String getUrlPrefix="http://localhost:8081/ts/user/HeadSculpture/";
    @GetMapping("/getImage")
    public String getImage(String fileName){
        String imagesDirPath = "/bishe/TS/images/";
        File file = new File(imagesDirPath + fileName);

        if (!file.exists()) {
            return JSONUtil.toJSONString(ResultUtil.error("图片文件不存在"));
        }

        byte[] bytes;
        try {
            bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            return JSONUtil.toJSONString(ResultUtil.error("图片获取失败！"));
        }

        return JSONUtil.toJSONString(ResultUtil.success(bytes));
    }
    @PostMapping("/changeheadsculpture")
    public String changeheadsculpture(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("token");
        String userid = JWTUtil.decodejwt(token).getClaim("userid").asString();
        try {
            // 生成新的文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String extension = getFileExtension(file.getOriginalFilename());
            String fileName = "user-" + uuid + "."+extension;
            //获取当前项目静态资源目录
            // 获取当前类的ClassLoader
            ClassLoader classLoader = getClass().getClassLoader();

            // 获取resources/static目录的URL
            URL resourceUrl = classLoader.getResource("static");
            String headStoreDir = "";
            if (resourceUrl != null) {
                // 获取绝对路径
                String absolutePath = new File(resourceUrl.getFile()).getAbsolutePath();
                System.out.println("Static resources directory: " + absolutePath);
                headStoreDir = absolutePath + baseUrl;
            } else {
                System.out.println("Static resources directory not found.");
            }
//            //获取当前年份，按年份分割文件夹
//            String year = String.valueOf(java.time.LocalDate.now().getYear());
//            // 拼接文件路径
//            String filePath = articleImagesDirPath+year;
            //如果不存在则创建该文件夹
            File fileDir = new File(headStoreDir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 保存文件
            file.transferTo(new File(headStoreDir, fileName));
            // 返回可直接访问的文件名
            String imageUrl=getUrlPrefix+fileName;
            int i = userService.changeHeadSculptureUrl(imageUrl, userid);
            user userInfoBySerial = userService.getUserInfoBySerial(userid);
            // 返回上传结果
            if (i!=0){
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("imageUrl",imageUrl);
                stringObjectHashMap.put("userInfo",userInfoBySerial);
                return JSONUtil.toJSONString(ResultUtil.success(stringObjectHashMap));
            }else {
                return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));
            }


        } catch (IOException ex) {
            // 处理异常
            return JSONUtil.toJSONString("Error occurred while uploading file: " + ex.getMessage());
        }
    }
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1);
    }
}
